import { injectable } from 'inversify';
import { AppState, AppStorage } from '@2/app/core/storage/app.storage';
import { Store } from 'pinia';
import { appDefineStore } from '@2/app/core/storage/define/app.define';
import { darkMode } from '@/settings/designSetting';
import { resetRouter } from '@/router';
import { Persistent } from '@/utils/cache/persistent';
import { ThemeEnum } from '@/enums/appEnum';
import { MenuSetting, ProjectConfig } from '#/config';
import { deepMerge } from '@/utils';
import { APP_DARK_MODE_KEY, PROJ_CFG_KEY } from '@/enums/cacheEnum';
import { DeepPartial } from 'unocss';
import { BeforeMiniState } from '#/store';

/**
 * @program: microservice-central-portal
 * @description: 系统状态定义存储接口实现
 * @author: baiHoo.chen
 * @create: 2022年5月26日
 **/
@injectable()
export class AppStorageImpl implements AppStorage {
  private readonly appStore: Store<string, AppState>;
  private timeId: TimeoutHandle | undefined;

  constructor() {
    this.appStore = appDefineStore();
  }
  /**
   * 销毁用户信息或状态信息
   */
  getDarkMode(): 'light' | 'dark' | string {
    return this.appStore.darkMode || localStorage.getItem(APP_DARK_MODE_KEY) || darkMode;
  }
  destroy(): void {
    resetRouter();
    Persistent.clearAll();
  }
  setDarkMode(mode: ThemeEnum): void {
    this.appStore.darkMode = mode;
    localStorage.setItem(APP_DARK_MODE_KEY, mode);
  }
  async setPageLoadingAction(loading: boolean): Promise<void> {
    if (loading) {
      clearTimeout(this.timeId);
      // Prevent flicker
      this.timeId = setTimeout(() => {
        this.appStore.setPageLoading(loading);
      }, 50);
    } else {
      this.appStore.setPageLoading(loading);
      clearTimeout(this.timeId);
    }
  }
  getProjectConfig(): ProjectConfig {
    return this.appStore.projectConfig || ({} as ProjectConfig);
  }
  setProjectConfig(config: DeepPartial<ProjectConfig>): void {
    this.appStore.projectConfig = deepMerge(this.appStore.projectConfig, config);
    Persistent.setLocal(PROJ_CFG_KEY, this.appStore.projectConfig);
  }
  getBeforeMiniInfo(): BeforeMiniState {
    return this.appStore.beforeMiniInfo;
  }
  setBeforeMiniInfo(state: BeforeMiniState): void {
    this.appStore.beforeMiniInfo = state;
  }
  getPageLoading(): boolean {
    return this.appStore.pageLoading;
  }
  setPageLoading(loading: boolean): void {
    this.appStore.pageLoading = loading;
  }
  getMenuSetting(): MenuSetting {
    return this.getProjectConfig().menuSetting;
  }
  setMenuSetting(setting: Partial<MenuSetting>): void {
    this.getProjectConfig()!.menuSetting = deepMerge(this.getProjectConfig()!.menuSetting, setting);
    Persistent.setLocal(PROJ_CFG_KEY, this.getProjectConfig());
  }
  /**
   * 返回需要使用的 定义存储对象{@see appDefineStoreWithOut}
   */
  useDefineStore(): Store<string, AppState> {
    return this.appStore;
  }
}
